package com.tanhua.common.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.common.config.AliyunConfig;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

@Service
public class PicUploadService {
    //允许上传的图片格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};
    @Autowired
    OSSClient ossClient;
    @Autowired
    AliyunConfig aliyunConfig; //生成连接阿里云上传文件对象
    public PicUploadResult upload(MultipartFile multipartFile) {
        PicUploadResult picUploadResult=new PicUploadResult();
        //校验上传文件的是否为图片后缀
        Boolean isLegal=false; //是否合格标记
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(),type)){
                isLegal=true;//符合
                break;
            }
        }
        if (!isLegal){
            picUploadResult.setStatus("error");
            return picUploadResult; //给出提示
        }
        //文件新的路径
        String filename = multipartFile.getOriginalFilename();
        //System.out.println(filename);
        String filePath = getFilePath(filename);//调用getFilePath方法获取到以日期为开头的新名
        //System.out.println(filePath);
        try{
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new
                    ByteArrayInputStream(multipartFile.getBytes()));
        }catch (Exception e){
            e.printStackTrace();//上传失败
            picUploadResult.setStatus("error");
            return picUploadResult;
        }
        //成功上传
        picUploadResult.setStatus("done");
        picUploadResult.setName(this.aliyunConfig.getUrlPrefix()+filePath);
       // System.out.println(picUploadResult.getName());
        picUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return picUploadResult;
    }
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
